<template>
  <div class="page-mobile-order">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="确认订单"
    ></white-header>
    <div class="goods-order">
      <div :class="['goods-thumbnail', kl_md.KLGL == 1 && 'gelin']">
        <img :src="course_obj.iconPath" />
      </div>
      <div class="goods-detail">
        <div class="goods-name">{{ course_obj.courseName }}</div>
        <div class="goods-info">
          {{ $t("locale.mobile.order.t1") }}：{{ $t("locale.mobile.order.t2") }}
          <!-- 拼团价 -->
          <template v-if="groupBooking == 1">
            {{ gbConfig.lastMoney }}
            <span :class="['price-market', groupBooking == 1 && 'price-group']">
              ￥{{ course_obj.price }}
            </span>
          </template>
          <template v-else>
            {{
              course_obj.isFree
                ? 0
                : course_obj.isDiscount
                ? course_obj.discountPrice
                : course_obj.price
            }}
            <span class="price-market" v-show="course_obj.isDiscount">
              ￥{{ course_obj.price }}
            </span>
          </template>
        </div>
        <div class="goods-info">
          {{ $t("locale.mobile.order.t3") }}：{{ getMajorName(course_obj) }}
        </div>
      </div>
    </div>
    <div class="goods-coupon" v-if="!course_obj.isDiscount && !groupBooking">
      <!-- <div class="discount" v-if="course_obj.isDiscount">
        <div>课程折扣</div>
        <div><span class="price">-￥{{course_obj.price-course_obj.discountPrice}}</span><span v-if="false">无可用折扣</span></div>
      </div> -->

      <div class="discount" v-if="isMemberFree && isMember">
        <div>会员限免</div>
        <div class="price">
          -￥{{
            course_obj.isFree
              ? 0
              : course_obj.isDiscount
              ? course_obj.discountPrice
              : course_obj.price
          }}
        </div>
      </div>
      <div
        class="discount"
        v-if="!course_obj.isDiscount && !isMemberFree && isMember"
      >
        <div>会员折扣价</div>
        <div>
          <!-- <span class="price">{{(member_discount.discount*10).toFixed(1)}}折</span> -->
          <span class="price"
            >￥{{
              Number(
                course_obj.isFree
                  ? 0
                  : isMemberFree
                  ? 0
                  : !isMember
                  ? course_obj.price
                  : user_member.memberLevel === 0
                  ? course_obj.smallMemberPrice
                  : user_member.memberLevel === 1
                  ? course_obj.middleMemberPrice
                  : user_member.memberLevel === 2
                  ? course_obj.highMemberPrice
                  : 0
              ).toFixed(2)
            }}</span
          >
          <span v-if="false">无可用折扣</span>
        </div>
      </div>
      <div class="discount" v-if="kl_md.KLYHJ == 1" @click="choiceCouponHandle">
        <div>平台优惠</div>
        <div class="coupon">
          <span
            class="price"
            v-if="useConponList.length > 0 && selectCouponIndex"
            >-￥{{ couponPrice.toFixed(2) }}</span
          >
          <span v-if="useConponList.length <= 0">无可用优惠</span>
          <span v-if="useConponList.length > 0 && !selectCouponIndex"
            >{{ useConponList.length }}张可用</span
          >
          <van-icon name="arrow" />
        </div>
      </div>
    </div>
    <div
      class="member-advert"
      v-if="member_config.isOpenMember === 1 && !isMember && !groupBooking"
    >
      <!-- <span class="advert-item" v-if="isShowSmallMemberAdvert">{{member_config.smallMemberName}}限免</span>
      <span class="advert-item" v-if="isShowMiddleMemberAdvert">{{member_config.middleMemberName}}限免</span>
      <span class="advert-item" v-if="isShowHighMemberAdvert">{{member_config.highMemberName}}限免</span> -->

      <van-tag plain type="primary" v-if="isShowSmallMemberAdvert"
        >{{ member_config.smallMemberName }}限免</van-tag
      >
      <van-tag plain type="primary" v-if="isShowMiddleMemberAdvert"
        >{{ member_config.middleMemberName }}限免</van-tag
      >
      <van-tag plain type="primary" v-if="isShowHighMemberAdvert"
        >{{ member_config.highMemberName }}限免</van-tag
      >
    </div>
    <div class="purchase-detail-pay_list" v-if="groupBooking != 1">
      <van-radio-group v-model="payType">
        <div class="pay_item ye_pay border-bottom" @click="payType = 1">
          <div class="pay_item_left">
            <img src="/img/mobile/account_menus_balance.png" alt="" />
            余额
          </div>
          <van-radio :name="1" />
        </div>
        <div :class="['pay_item','wx_pay',!is_in_wechat ? 'border-bottom' : '']" @click="payType = 2">
          <div class="pay_item_left">
            <img src="/img/mobile/member_payment_wechat.png" alt="" />
            微信
          </div>
          <van-radio :name="2" />
        </div>
        <div
          class="pay_item zfb_pay"
          @click="payType = 3"
          v-show="!is_in_wechat"
        >
          <div class="pay_item_left">
            <img src="/img/mobile/member_payment_alipay.png" alt="" />
            支付宝
          </div>
          <van-radio :name="3" />
        </div>
      </van-radio-group>
    </div>
    <div class="bottom-area">
      <van-submit-bar
        v-if="groupBooking == 1"
        :price="
          group_booking_status == 1
            ? gbConfig.lastMoney * 100
            : course_obj.price * 100
        "
        :button-text="$t('locale.mobile.order.t4')"
        @submit="GroupBookingSubmit"
      />
      <van-submit-bar
        v-else
        :price="
          ((course_obj.isFree
            ? 0
            : course_obj.isDiscount
            ? course_obj.discountPrice
            : isMemberFree
            ? 0
            : !isMember
            ? course_obj.price
            : user_member.memberLevel === 0
            ? course_obj.smallMemberPrice
            : user_member.memberLevel === 1
            ? course_obj.middleMemberPrice
            : user_member.memberLevel === 2
            ? course_obj.highMemberPrice
            : 0) -
            couponPrice) *
            100
        "
        :button-text="$t('locale.mobile.order.t4')"
        @submit="onSubmit"
      />
    </div>
    <van-action-sheet v-model="isShowCouponList" title="选择优惠卷">
      <div
        class="coupon-content"
        v-for="(item, index) in useConponList"
        :key="item.id"
        v-if="item.use === 1"
      >
        <div class="coupon-box">
          <div class="box-left">
            <div class="price">
              ￥<span>{{ item.couponAmount }}</span>
            </div>
            <div class="info">
              <div class="max-time">
                <span v-if="item.couponType == 0"
                  >满{{ item.conditionalAmount }}可用</span
                >
                <span v-if="item.couponType == 1">无门槛</span>
              </div>
              <div class="info-time">
                有效期至 {{ formatDate(item.endTime) }}
              </div>
            </div>
          </div>
          <div class="box-right" @click="useCoupon(item.id)">
            立即使用
          </div>
        </div>
      </div>
      <div class="clear-coupon-btn" @click="clearCouponHandle">
        不使用优惠卷
      </div>
    </van-action-sheet>
    <van-action-sheet v-model="isShowPayList" title="选择支付方式">
      <div class="pay_list">
        <van-radio-group v-model="payType">
          <div class="pay_item ye_pay" @click="payType = 1">
            <div class="pay_item_left">
              <img src="/img/mobile/account_menus_balance.png" alt="" />
              余额
            </div>
            <van-radio :name="1" />
          </div>
          <div
            class="pay_item wx_pay"
            @click="payType = 2"
          >
            <div class="pay_item_left">
              <img src="/img/mobile/member_payment_wechat.png" alt="" />
              微信
            </div>
            <van-radio :name="2" />
          </div>
          <div
            class="pay_item zfb_pay"
            @click="payType = 3"
            v-show="!is_in_wechat"
          >
            <div class="pay_item_left">
              <img src="/img/mobile/member_payment_alipay.png" alt="" />
              支付宝
            </div>
            <van-radio :name="3" />
          </div>
        </van-radio-group>
        <div class="pay_item pay_btn" @click="handlePay()">确认支付</div>
      </div>
    </van-action-sheet>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { getUserCoupon } from "~/api/coupon";
import { getCourse } from "~/api/course";
import { wexinPay, wxJspay } from "~/utils/pay";
import {
  getMemberInfo,
  getMember,
  getMemberList,
  getMemberConfig
} from "~/api/member";
import {
  saveOrder,
  generateOrder,
  getCourseBuyToH5Alipay,
  getCourseBuyToH5Wx,
  getCourseBuyWxAuthorization,
  getCourseBuyWxBrowserPay,
  getCourseBuyWxAppPay,
  getCourseBuyAlipayAppPay
} from "~/api/order";
import {
  getGroupBookingListByCourse,
  publishGroup,
  joinGroup,
  getGroupBookingGroupsByCourse,
  getGroupBookingGroupsById,
  groupGoodsBuy
} from "~/api/group-booking";
import _templete from "../../components/_templete.vue";
import { baseUrl, socketUrl } from "~/config/conf";

export default {
  components: {
    WhiteHeader
  },
  data() {
    return {
      isShowPayList: false,
      payType: 1,
      orderNo: "",
      websock: null,
      timer: null, //节流计时器
      socketFailedCount: 0, //socket重连计数器
      orderNo: "",

      couponPrice: 0,
      isShowCouponList: false,
      couponList: [],
      selectCouponIndex: null,
      course_obj: {},
      isMemberFree: false,
      isMember: false,
      memberList: [],
      member_config: {},
      gbConfig: {
        creatTime: 1612594549000,
        endTime: 1643644800000,
        goodsId: 12,
        id: 5,
        imitate: 1,
        lastMoney: 1800,
        personNum: 2,
        startTime: 1612594449000,
        troopsTime: 1440,
        is_set: false // 是否是拼团商品
      }, //拼团信息
      group: {
        creatTime: 0,
        goodsId: -1,
        personNum: -1,
        userId: -1,
        userIds: [],
        userList: [
          {
            acName: "",
            avatar: "",
            id: -1
          }
        ]
      }
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      major_list(state) {
        return state.major_list;
      },
      member_discount(state) {
        return state.member_discount;
      },
      user_member(state) {
        return state.member_info;
      },
      kl_md(state) {
        return state.kl_md;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      }
    }),
    isWxAuthorization() {
      if (this.$route.query.isWxAuthorization) {
        return true;
      } else {
        return false;
      }
    },
    currentOrderNo() {
      return this.$route.query.orderNo || this.orderNo || "";
    },
    courseId() {
      return this.$route.query.id;
    },
    //是否为拼团订单
    groupBooking() {
      return this.$route.query.groupBooking;
    },
    //加入拼团
    joinGroup() {
      return this.$route.query.joinGroup;
    },
    //1.允许拼团  2.拼团还没开始  3.拼团结束
    group_booking_status() {
      const { endTime, startTime } = this.gbConfig;
      let currentTime = new Date().getTime();
      if (startTime <= currentTime && currentTime < endTime) {
        return 1;
      } else if (startTime > currentTime) {
        return 2;
      } else if (endTime < currentTime) {
        return 3;
      }
    },
    isShowSmallMemberAdvert() {
      if (this.member_config.isOpenMember === 1 && this.memberList.length > 0) {
        if (
          JSON.parse(this.memberList[0].majorIds).includes(
            this.course_obj.majorId
          )
        ) {
          // console.log("该课程在初级免费专业中");
          return true;
        } else if (
          JSON.parse(this.memberList[0].courseIds).includes(this.course_obj.id)
        ) {
          // console.log("该课程在初级免费课程中");
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    isShowMiddleMemberAdvert() {
      if (this.member_config.isOpenMember === 1 && this.memberList.length > 0) {
        if (
          JSON.parse(this.memberList[1].majorIds).includes(
            this.course_obj.majorId
          )
        ) {
          // console.log("该课程在中级免费专业中");
          return true;
        } else if (
          JSON.parse(this.memberList[1].courseIds).includes(this.course_obj.id)
        ) {
          // console.log("该课程在中级免费课程中");
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    isShowHighMemberAdvert() {
      if (this.member_config.isOpenMember === 1 && this.memberList.length > 0) {
        if (
          JSON.parse(this.memberList[2].majorIds).includes(
            this.course_obj.majorId
          )
        ) {
          // console.log("该课程在高级免费专业中");
          return true;
        } else if (
          JSON.parse(this.memberList[2].courseIds).includes(this.course_obj.id)
        ) {
          // console.log("该课程在高级免费课程中");
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    useConponList() {
      let time = new Date().getTime();
      let price =
        ((this.course_obj.isFree
          ? 0
          : this.isMemberFree
          ? 0
          : this.course_obj.isDiscount
          ? this.course_obj.discountPrice
          : !this.isMember
          ? this.course_obj.price
          : this.user_member.memberLevel === 0
          ? this.course_obj.smallMemberPrice
          : this.user_member.memberLevel === 1
          ? this.course_obj.middleMemberPrice
          : this.user_member.memberLevel === 2
          ? this.course_obj.highMemberPrice
          : 0) -
          this.couponPrice) *
        1;
      let newCouponList = this.couponList.filter(
        item =>
          item.open == 1 &&
          item.status == 1 &&
          item.startTime <= time &&
          item.endTime >= time
      );
      let couponTwoList = newCouponList
        .filter(item => {
          if (item.couponGoodType == 1) {
            return true;
          }
          return JSON.parse(item.goods).includes(this.courseId * 1);
        })
        .map(item => {
          if (item.couponType === 0 && item.conditionalAmount <= price) {
            // console.log("符合满减要求", price);
            return { ...item, use: 1 };
          } else if (item.couponType === 1 && item.couponAmount <= price) {
            // console.log("符合无门槛要求", price);
            return { ...item, use: 1 };
          } else {
            return item;
          }
        });
      return couponTwoList;
    }
  },
  watch: {
    currentOrderNo:{
      handler:function(oldV,newV){
        if(this.$route.query.orderNo || this.orderNo){
          this.initWebSocket();
        }
      },
      immediate:true
    }
    // currentOrderNo(){
    //   if(this.$route.query.orderNo || this.orderNo){
    //     this.initWebSocket();
    //   }
    // }
  },
  activated() {
    this.initData();
  },
  deactivated(){
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  destroyed(){
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  methods: {
    ...mapActions([
      "initMajorList",
      "initMember",
      "initBuyCourseRecord",
      "initBuyRecord"
    ]),
    ...mapMutations([
      "SET_IS_LOADING",
      "UPDATE_USERINFO",
      "UPDATE_BUYRECORD_LIST",
      "SET_MEMBER_DISCOUNT"
    ]),
    initWebSocket() {
      if (process.client) {
        if ("WebSocket" in window) {
          //初始化weosocket
          const wsuri = socketUrl + "buyOrderInfo/" + this.currentOrderNo;
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;

          window.addEventListener("beforeunload", this.closeConnection, false);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t134"));
        }
      }
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      clearTimeout(this.timer);
      this.timer = null;
      this.socketFailedCount = 0;
    },
    websocketonerror() {
      //连接建立失败重连
      console.log("socket连接失败！");
      this.retryConnectSocket();
    },
    websocketonmessage(e) {
      //数据接收
      console.log("收到socket:", e);
      console.log(e.data || e);
      try {
        const result = JSON.parse(e.data);
        if (result.code == 200) {
          let courseId = result.data.productId;
          // 付款成功
          // this.pay_success = true;
          this.paySuccess(courseId);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t128"));
        }
      } catch (e) {
        console.log(e);
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    async websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      this.retryConnectSocket();
    },
    closeConnection() {
      return new Promise((res, rej) => {
        try {
          window.removeEventListener("beforeunload", this.closeConnection);
          this.websock && this.websock.close();

          if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
            this.socketFailedCount = 0;
          }
        } catch (e) {
          console.log("关闭socket错误：", e);
        }
        res();
      }).then();
    },
    retryConnectSocket() {
      this.debounce(async () => {
        this.socketFailedCount = this.socketFailedCount + 1;
        if (this.socketFailedCount < 10) {
          await this.closeConnection();
          this.initWebSocket();
        } else {
          console.info("websocket fail to connection , please retry later!");
          this.timer = null;
        }
      }, 3000);
    },
    debounce(fn, wait) {
      return !(() => {
        if (this.timer !== null) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(fn, wait);
      })();
    },
    async handlePay() {
      let __price__ = Number(
        this.course_obj.isFree
          ? 0
          : this.course_obj.isDiscount
          ? this.course_obj.discountPrice
          : this.isMemberFree
          ? 0
          : !this.isMember
          ? this.course_obj.price
          : this.user_member.memberLevel === 0
          ? this.course_obj.smallMemberPrice
          : this.user_member.memberLevel === 1
          ? this.course_obj.middleMemberPrice
          : this.user_member.memberLevel === 2
          ? this.course_obj.highMemberPrice
          : 0
      ).toFixed(2);
      if (this.payType == 1) {
        console.log("余额支付");
        this.$dialog
          .confirm({
            title: this.$t("locale.mobile.order.t6"),
            message:
              this.$t("locale.mobile.order.t7") +
              (__price__ - this.couponPrice).toFixed(2) +
              this.$t("locale.mobile.order.t8")
          })
          .then(async () => {
            console.log(__price__ - this.couponPrice, this.user_info.balance);
            if (__price__ - this.couponPrice > this.user_info.balance) {
              this.$dialog
                .confirm({
                  title: this.$t("locale.mobile.order.t9"),
                  message:
                    this.$t("locale.mobile.order.t10") +
                    (
                      __price__ -
                      this.couponPrice -
                      this.user_info.balance
                    ).toFixed(2) +
                    this.$t("locale.mobile.order.t11"),
                  confirmButtonText: this.$t("locale.mobile.order.t12")
                })
                .then(() => {
                  this.$router.push({
                    path: "/m/wallet",
                    query: {
                      num: (
                        __price__ -
                        this.couponPrice -
                        this.user_info.balance
                      ).toFixed(2),
                      rdurl: this.$route.fullPath
                    }
                  });
                });
            } else {
              this.SET_IS_LOADING(true);
              let params = {
                courseId: this.courseId,
                userId: this.user_info.id,
                price: this.turnString(__price__),
                ip: returnCitySN.cip
              };
              if (this.selectCouponIndex) {
                params = {
                  ...params,
                  couponId: this.selectCouponIndex
                };
              }
              let result = await saveOrder(params);
              if (result && result.data && result.data.code == 200) {
                const {
                  balance,
                  id,
                  courseId,
                  userId,
                  deleted
                } = result.data.data;
                let update_obj = {
                  balance
                };
                let course_update_obj = {
                  id,
                  courseId,
                  userId,
                  deleted
                };
                console.log("更新课程", course_update_obj);
                console.log("更新课程", result.data.data);
                this.$store.dispatch({
                  type: "checkBingWechatStatus",
                  payload: {
                    type: "pay",
                    params: {
                      courseName: this.course_obj.courseName,
                      userId,
                      orderNum: new Date().getTime() + "_" + userId,
                      payTime: this.trimDate(new Date()),
                      money: params.price
                    }
                  }
                });
                this.UPDATE_USERINFO(update_obj);
                this.UPDATE_BUYRECORD_LIST(course_update_obj);
                this.SET_IS_LOADING(false);
                this.$toast(this.$t("locale.mobile.order.t13"));
                this.$router.replace("/m/course-detail?id=" + this.courseId);
              } else {
                this.SET_IS_LOADING(false);
                if (result && result.data && result.data.code == 420) {
                  this.$toast(this.$t("locale.mobile.order.t14"));
                } else if (result && result.data && result.data.code == 1001) {
                  this.$toast("课程购买人数达到上限！");
                } else {
                  this.$toast(this.$t("locale.mobile.order.t15"));
                }
              }
            }
          })
          .catch(() => {});
      } else if (this.payType == 2) {
        if(!this.currentOrderNo){
          let params = {
            courseId: this.courseId,
            userId: this.user_info.id,
            price: this.turnString(__price__),
            ip: returnCitySN.cip,
            type: 1,
            payType: 2
          };
          if (this.selectCouponIndex) {
            params = {
              ...params,
              couponId: this.selectCouponIndex
            };
          }
          let result = await generateOrder(params);
          if (result && result.data && result.data.code == 200) {
            const { orderNo } = result.data.data;
            this.orderNo = orderNo;
          } else if (result && result.data && result.data.code == 420) {
            this.$toast(this.$t("locale.mobile.order.t14"));
          } else if (result && result.data && result.data.code == 1001) {
            this.$toast("课程购买人数达到上限！");
          } else {
            this.$toast(this.$t("locale.mobile.order.t15"));
          }
        }
        if (this.is_in_wechat) {
          if (this.is_in_minigram) {
            wx.miniProgram.navigateTo({
              url: `/pages/buypay/index?orderNo=${this.currentOrderNo}`,
              success: function() {
                console.log("成功跳转小程序");
              },
              fail: function() {
                console.log("跳转小程序失败");
                this.$toast("小程序微信支付暂不可用");
              },
              complete: function() {
                console.log("完成");
              }
            });
            // this.$toast("小程序微信支付暂不可用");
          } else {
            // 进行微信授权--此处要修改-去掉授权
            if(this.isWxAuthorization){
              let WxBrowserPayResult = await getCourseBuyWxBrowserPay({orderNo:this.currentOrderNo});
                if (WxBrowserPayResult && WxBrowserPayResult.data && WxBrowserPayResult.data.code == 200) {
                    const { data } = WxBrowserPayResult.data;
                    console.log(
                    "=====================微信JS支付====================="
                    );
                    wxJspay(
                    data,
                    res => {
                        console.log("微信JS支付结果：", res);
                    },
                    err => {
                        console.log(err);
                    }
                    );
                } else {
                  this.$toast("调起失败");
                }
            }else{
              let WxAuthorizationResult = await getCourseBuyWxAuthorization({orderNo:this.currentOrderNo});
              if (WxAuthorizationResult && WxAuthorizationResult.data && WxAuthorizationResult.data.code == 200) {
                window.location.href = WxAuthorizationResult.data.msg;
              } else {
                this.$toast(this.$t("locale.mobile.login.t19"));
              }
            }
            
          }
        } else {
          if (window.hasOwnProperty("flutter_inappwebview")) {
            // this.$toast("进来了")
              console.log(
                "=====================微信App支付====================="
              );
              let appPayresult = await getCourseBuyWxAppPay({orderNo:this.currentOrderNo});
              if (appPayresult && appPayresult.data && appPayresult.data.code == 200) {
                // this.$toast("调起支付成功")
                const {
                  appid,
                  partnerid,
                  noncestr,
                  timestamp,
                  sign,
                  prepayid,
                  amount
                } = appPayresult.data.data;
                let arg = JSON.stringify({
                  type: "wxpay",
                  data: {
                    appId: appid,
                    partnerId: partnerid,
                    prepayId: prepayid,
                    packageValue: appPayresult.data.data.package,
                    nonceStr: noncestr,
                    timeStamp: timestamp,
                    sign: sign,
                    amount: amount
                  }
                });
                // this.$toast(arg)
                window.flutter_inappwebview
                  .callHandler("Pay", arg)
                  .then(res => {
                    console.log("微信支付成功！");
                    console.log(res);
                  }).catch(err=>{
                    this.$toast("支付失败")
                  });
              } else {
                this.$toast(
                  '支付失败' + result.data
                    ? result.data.msg
                    : null
                );
              }
          }else{
            console.log("=====================微信H5支付=====================");
            let H5WxResult = await getCourseBuyToH5Wx({orderNo:this.currentOrderNo});
            if (H5WxResult && H5WxResult.data && H5WxResult.data.code == 200) {
              const { data } = H5WxResult.data;
              let redirect_url = window.location.href + "&orderNo=" + this.currentOrderNo + "&isSuccess=1";
              window.location.href = `${
                data.mweb_url
              }&redirect_url=${encodeURIComponent(redirect_url)}`;
            } else {
              this.$toast(
                this.$t("locale.mobile.wallet.t24") + H5WxResult.data
                  ? H5WxResult.data.msg
                  : null
              );
            }
          }
        }
      } else if (this.payType == 3) {
        let params = {
            courseId: this.courseId,
            userId: this.user_info.id,
            price: this.turnString(__price__),
            ip: returnCitySN.cip,
            type: 1,
            payType: 3
          };
          if (this.selectCouponIndex) {
            params = {
              ...params,
              couponId: this.selectCouponIndex
            };
          }
          let result = await generateOrder(params);
          if (result && result.data && result.data.code == 200) {
            const { orderNo } = result.data.data;
            this.orderNo = orderNo;
            if (window.hasOwnProperty("flutter_inappwebview")) {
                console.log(
                  "=====================支付宝App支付====================="
                );
                let aliPayResult = await getCourseBuyAlipayAppPay({orderNo:this.currentOrderNo});
                if (aliPayResult && aliPayResult.data && aliPayResult.data.code == 200) {
                  let arg = JSON.stringify({
                    type: "alipay",
                    data: aliPayResult.data.data
                  });
                  window.flutter_inappwebview.callHandler("Pay", arg).then(res => {
                    console.log("支付宝支付成功！");
                    console.log(res);
                  });
                } else {
                  this.$toast(
                    "支付成功" + aliPayResult.data
                      ? aliPayResult.data.msg
                      : null
                  );
                }
            }else{
              console.log("=====================支付宝支付=====================");
              let resultPay = await getCourseBuyToH5Alipay(this.orderNo);
              if (resultPay && resultPay.data && resultPay.data.code == 200) {
                window.location.href = resultPay.data.data;
              } else {
                this.$toast(
                  this.$t("locale.mobile.wallet.t24") + resultPay.data
                    ? resultPay.data.msg
                    : null
                );
              }
            }
          } else if (result && result.data && result.data.code == 420) {
            this.$toast(this.$t("locale.mobile.order.t14"));
          } else if (result && result.data && result.data.code == 1001) {
            this.$toast("课程购买人数达到上限！");
          } else {
            this.$toast(this.$t("locale.mobile.order.t15"));
          }
      } else {
        this.$toast("请选择您的支付方式");
      }
      return;
    },
    choiceCouponHandle() {
      if (this.useConponList.length > 0) {
        this.isShowCouponList = true;
      } else {
        return;
      }
    },
    useCoupon(id) {
      this.selectCouponIndex = id;
      let coupon = this.couponList.find(item => item.id == id);
      this.couponPrice = coupon && coupon.couponAmount;
      this.isShowCouponList = false;
    },
    clearCouponHandle() {
      this.isShowCouponList = false;
      this.couponPrice = 0;
      this.selectCouponIndex = null;
    },
    //格式化时间
    formatDate(date) {
      var date = new Date(date);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },
    async getMemberConfig() {
      this.SET_IS_LOADING(true);
      let result = await getMemberConfig();
      // console.log("result会员", result);
      if (result && result.data && result.data.code == 200) {
        this.member_config = {
          smallMemberName: result.data.data.smallMemberName,
          middleMemberName: result.data.data.middleMemberName,
          highMemberName: result.data.data.highMemberName,
          isOpenMember: result.data.data.isOpenMember
        };
        console.log(this.member_info);
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    async getMemberList() {
      this.SET_IS_LOADING(true);
      let result = await getMemberList();
      // console.log("result", result);
      if (result && result.data && result.data.code == 200) {
        this.memberList = result.data.data.rows.map(item => {
          return { ...item, introduction: JSON.parse(item.introduction) };
        });
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    async getMember() {
      this.SET_IS_LOADING(true);
      let result = await getMember(this.user_info.id);
      // console.log("result", result);
      if (result && result.data && result.data.code == 200) {
        this.isMember = !!result.data.data;
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    async getMemberInfo() {
      let memberDiscount = await getMemberInfo(this.user_info.id);
      if (
        memberDiscount.data.data.majorIds.includes(this.course_obj.majorId) ||
        memberDiscount.data.data.courseIds.includes(Number(this.courseId))
      ) {
        this.isMemberFree = true;
      } else {
        this.isMemberFree = false;
      }
      this.SET_MEMBER_DISCOUNT(memberDiscount.data.data);
    },
    async getData() {
      return new Promise(async (res, rej) => {
        this.SET_IS_LOADING(true);
        let result = await getCourse({
          id: this.courseId
        });
        if (result && result.data && result.data.code == 200) {
          const { data } = result.data;
          if (data && data.rows && data.rows.length > 0) {
            // this.course_obj = data.rows[0];
            // 加一层折扣时间的判断,不在折扣时间内判定为不是折扣课程
            let course = data.rows[0];
            let currentTime = new Date().getTime();
            if(!(course.isDiscount == 1 && currentTime >= course.discountStartTime && course.discountEndTime >= currentTime)){
              this.course_obj = {
                ...course,
                isDiscount:0
              }
            }else{
              this.course_obj = course;
            }
          }
        } else {
          this.$toast(
            this.$t("locale.mobile.order.t5") + result && result.data.msg
          );
        }
        this.SET_IS_LOADING(false);
        res();
      }).then();
    },
    async getCouponList() {
      let result = await getUserCoupon(this.user_info.id);
      if (result && result.data && result.data.code == 200) {
        this.couponList = result.data.data.currentCoupon;
      } else {
        // this.$toast("获取失败！");
      }
      // console.log("我的优惠卷",result);
    },
    getMajorName(item) {
      let res = this.major_list.filter(i => i.id == item.majorId);
      if (res.length > 0) {
        return res[0].name;
      } else {
        return this.$t("locale.mobile.order.unknow");
      }
    },
    turnString(num) {
      var re = /^[0-9]+$/;
      var re2 = /^[0-9]+(\.[0-9]{1})$/;
      if (re.test(num)) {
        num += ".00";
      }
      if (re2.test(num)) {
        num += "0";
      }
      return num;
    },
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        return `${_date.getFullYear()}.${_date.getMonth() +
          1}.${_date.getDate()}  ${_date.getHours()}:${_date.getMinutes()}:${_date.getSeconds()}`;
      } else {
        return this.$t("locale.mobile.wallet.unknow");
      }
    },
    onSubmit() {
      // this.isShowPayList = true;
      this.handlePay();
      return;
      // let __price__ = this.course_obj.isFree
      //   ? 0
      //   : this.course_obj.isDiscount
      //   ? this.course_obj.discountPrice
      //   : this.course_obj.price;

      // let __price__ = this.isMemberFree?0:
      //     this.isMember?(this.course_obj.isFree
      //       ? 0
      //       : this.course_obj.isDiscount
      //       ? this.course_obj.discountPrice
      //       : this.course_obj.price)*this.member_discount.discount:(this.course_obj.isFree
      //       ? 0
      //       : this.course_obj.isDiscount
      //       ? this.course_obj.discountPrice
      //       : this.course_obj.price)

      let __price__ = Number(
        this.course_obj.isFree
          ? 0
          : this.course_obj.isDiscount
          ? this.course_obj.discountPrice
          : this.isMemberFree
          ? 0
          : !this.isMember
          ? this.course_obj.price
          : this.user_member.memberLevel === 0
          ? this.course_obj.smallMemberPrice
          : this.user_member.memberLevel === 1
          ? this.course_obj.middleMemberPrice
          : this.user_member.memberLevel === 2
          ? this.course_obj.highMemberPrice
          : 0
      ).toFixed(2);
      this.$dialog
        .confirm({
          title: this.$t("locale.mobile.order.t6"),
          message:
            this.$t("locale.mobile.order.t7") +
            (__price__ - this.couponPrice).toFixed(2) +
            this.$t("locale.mobile.order.t8")
        })
        .then(async () => {
          console.log(__price__ - this.couponPrice, this.user_info.balance);
          if (__price__ - this.couponPrice > this.user_info.balance) {
            this.$dialog
              .confirm({
                title: this.$t("locale.mobile.order.t9"),
                message:
                  this.$t("locale.mobile.order.t10") +
                  (
                    __price__ -
                    this.couponPrice -
                    this.user_info.balance
                  ).toFixed(2) +
                  this.$t("locale.mobile.order.t11"),
                confirmButtonText: this.$t("locale.mobile.order.t12")
              })
              .then(() => {
                this.$router.push({
                  path: "/m/wallet",
                  query: {
                    num: (
                      __price__ -
                      this.couponPrice -
                      this.user_info.balance
                    ).toFixed(2),
                    rdurl: this.$route.fullPath
                  }
                });
              });
          } else {
            this.SET_IS_LOADING(true);
            let params = {
              courseId: this.courseId,
              userId: this.user_info.id,
              price: this.turnString(__price__),
              ip: returnCitySN.cip
            };
            if (this.selectCouponIndex) {
              params = {
                ...params,
                couponId: this.selectCouponIndex
              };
            }
            let result = await saveOrder(params);
            if (result && result.data && result.data.code == 200) {
              const {
                balance,
                id,
                courseId,
                userId,
                deleted
              } = result.data.data;
              let update_obj = {
                balance
              };
              let course_update_obj = {
                id,
                courseId,
                userId,
                deleted
              };
              console.log("更新课程", course_update_obj);
              console.log("更新课程", result.data.data);
              this.$store.dispatch({
                type: "checkBingWechatStatus",
                payload: {
                  type: "pay",
                  params: {
                    courseName: this.course_obj.courseName,
                    userId,
                    orderNum: new Date().getTime() + "_" + userId,
                    payTime: this.trimDate(new Date()),
                    money: params.price
                  }
                }
              });
              this.UPDATE_USERINFO(update_obj);
              this.UPDATE_BUYRECORD_LIST(course_update_obj);
              this.SET_IS_LOADING(false);
              this.$toast(this.$t("locale.mobile.order.t13"));
              this.$router.replace("/m/course-detail?id=" + this.courseId);
            } else {
              this.SET_IS_LOADING(false);
              if (result && result.data && result.data.code == 420) {
                this.$toast(this.$t("locale.mobile.order.t14"));
              } else if (result && result.data && result.data.code == 1001) {
                this.$toast("课程购买人数达到上限！");
              } else {
                this.$toast(this.$t("locale.mobile.order.t15"));
              }
            }
          }
        })
        .catch(() => {});
    },
    //拼团
    async getGroupBooking() {
      this.SET_IS_LOADING(true);
      let result = await getGroupBookingListByCourse({
        goodsId: this.courseId
      });
      console.log("拼团信息：", result);
      if (result && result.data && result.data.code == 200) {
        const { rows } = result.data.data;
        if (rows.length > 0) {
          this.gbConfig = { ...rows[0], is_set: true };
        } else {
          this.gbConfig = {
            creatTime: new Date().getTime(),
            endTime: new Date().getTime(),
            goodsId: -1,
            imitate: 1,
            lastMoney: 0,
            personNum: 2,
            startTime: new Date().getTime(),
            troopsTime: 0,
            is_set: false // 是否是拼团商品
          };
          this.$dialog.alert({
            title: "提示",
            message: "该课程不能参与拼团！",
            confirmButtonText: "确认",
            confirm: () => {
              this.$router.back();
            }
          });
        }
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    //发起拼团
    async GroupBookingSubmit() {
      if (this.gbConfig.lastMoney > this.user_info.balance) {
        this.$dialog
          .confirm({
            title: this.$t("locale.mobile.order.t9"),
            message:
              this.$t("locale.mobile.order.t10") +
              (this.gbConfig.lastMoney - this.user_info.balance).toFixed(2) +
              this.$t("locale.mobile.order.t11"),
            confirmButtonText: this.$t("locale.mobile.order.t12")
          })
          .then(() => {
            this.$router.push({
              path: "/m/wallet",
              query: {
                num: (this.gbConfig.lastMoney - this.user_info.balance).toFixed(
                  2
                ),
                rdurl: this.$route.fullPath
              }
            });
          });
        return;
      }
      this.SET_IS_LOADING(true);
      if (this.joinGroup) {
        console.log(this.group);
        let params = {
          groupPurchaseGoodsId: this.gbConfig.id,
          goodsTroopsId: this.joinGroup,
          userId: this.user_info.id,
          ip: returnCitySN.cip
        };
        let result = await groupGoodsBuy(params);
        console.log("参与团购下单:", result);
        if (result && result.data && result.data.code == 200) {
          const { balance } = result.data.data;
          let update_obj = {
            balance
          };
          this.UPDATE_USERINFO(update_obj);
          this.initBuyCourseRecord();
          this.initBuyRecord();
          this.$toast(this.$t("locale.mobile.order.t13"));
          this.$router.replace("/m/course-detail?id=" + this.courseId);
        } else {
          if (result && result.data.code == 206) {
            const msg = "余额不足";
            this.$toast(this.$t("locale.mobile.order.t15") + msg);
          } else if (result && result.data.code == 400) {
            const msg = "您已经购买过该课程！";
            this.$toast(msg);
          } else {
            this.$toast(this.$t("locale.mobile.order.t15"));
          }
        }
      } else {
        let params = {
          groupPurchaseGoodsId: this.gbConfig.id,
          userId: this.user_info.id,
          ip: returnCitySN.cip
        };
        let result = await groupGoodsBuy(params);
        console.log("发起团购下单:", result);
        if (result && result.data && result.data.code == 200) {
          const { balance } = result.data.data;
          let update_obj = {
            balance
          };
          this.UPDATE_USERINFO(update_obj);
          this.$toast(this.$t("locale.mobile.order.t13"));
          this.$router.replace("/m/course-detail?id=" + this.courseId);
        } else {
          if (result && result.data.code == 206) {
            const msg = "余额不足";
            this.$toast(this.$t("locale.mobile.order.t15") + msg);
          } else if (result && result.data.code == 400) {
            const msg = "您已经购买过该课程！";
            this.$toast(msg);
          } else {
            this.$toast(this.$t("locale.mobile.order.t15"));
          }
        }
      }
      this.SET_IS_LOADING(false);
    },
    //获取拼团团队
    async getGroupsByCourse() {
      this.SET_IS_LOADING(true);
      const { id } = this.gbConfig;
      if (id) {
        let result = await getGroupBookingGroupsById(this.joinGroup);
        console.log("获取拼团团队:", result);
        if (result && result.data && result.data.code == 200) {
          const { data } = result.data;
          if (data) {
            this.group = {
              ...data
            };
          } else {
            this.$toast("该拼单不存在!");
            this.$router.back();
          }
        } else {
        }
      }
      this.SET_IS_LOADING(false);
    },
    initData() {
      if (process.client) {
        if (!this.token && Object.keys(this.user_info).length == 0) {
          this.$router.replace("/m/login");
          return;
        }
      }
      this.getData();
      this.initMajorList();
      this.getMemberInfo();
      this.getMember();
      this.initMember();
      this.getMemberList();
      this.getMemberConfig();
      this.getCouponList();
      if (this.groupBooking) {
        this.getGroupBooking();
        if (this.group_booking_status == 3) {
          this.$dialog.alert({
            title: "提示",
            message: "该课程拼团已经结束！继续购买将使用原价购买",
            confirmButtonText: "确认"
          });
        } else if (this.group_booking_status == 2) {
          this.$dialog.alert({
            title: "提示",
            message: "该课程拼团还未开始！",
            confirmButtonText: "确认"
          });
        }
        if (this.joinGroup) {
          this.getGroupsByCourse();
        }
      }
    },
    paySuccess(courseId) {
      let id = courseId || this.courseId;
      this.initBuyRecord();
      this.$toast("购买成功");
      this.$router.replace("/m/course-detail?id=" + id);
    },
    async wxBrowserPay(){
      if(this.isWxAuthorization){
        let WxBrowserPayResult = await getCourseBuyWxBrowserPay({orderNo:this.currentOrderNo});
          if (WxBrowserPayResult && WxBrowserPayResult.data && WxBrowserPayResult.data.code == 200) {
              const { data } = WxBrowserPayResult.data;
              console.log(
              "=====================微信JS支付====================="
              );
              wxJspay(
              data,
              res => {
                  console.log("微信JS支付结果：", res);
              },
              err => {
                  console.log(err);
              }
              );
          } else {
            this.$toast("调起失败");
          }
      }
    }
  },
  created() {
    if (this.$route.query.isSuccess == 1) {
      // 支付成功
      this.paySuccess();
      // this.pay_success = true;
    } else {
      this.initData();
      this.wxBrowserPay();
    }
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
.page-mobile-order {
  .pay_list {
    padding: 0.384rem 0.192rem 0.3rem;
    .pay_item {
      width: 100%;
      height: 0.8448rem;
      border-radius: 0.1rem;
      margin-bottom: 0.2rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 0.3rem;
      box-sizing: border-box;
      padding: 0 0.2rem;
      border: 1px solid var(--theme-color);
      .pay_item_left {
        display: flex;
        align-items: center;
        img {
          width: 0.48rem;
          height: 0.48rem;
          display: block;
          margin-right: 0.14rem;
        }
      }
      // &.ye_pay{
      //   border: 1px solid #515a6e;
      // }
      // &.wx_pay{
      //   border: 1px solid #00c800;
      // }
      // &.zfb_pay{
      //   border: 1px solid #2194d3;
      // }
      &.pay_btn {
        background: var(--theme-color);
        color: #ffffff;
        font-size: 0.3rem;
        margin-top: 0.5rem;
        display: flex;
        justify-content: center;
      }
    }
  }
}
</style>
<style lang="scss">
.page-mobile-order {
  padding: 0.1rem 0.2rem;
  .van-button {
    font-size: 0.3rem;
  }
  .coupon-content {
    width: 7.2rem;
    height: 2rem;
    background-color: #ffffff;
    .coupon-box {
      width: 6.6rem;
      height: 1.6rem;
      margin: 0 auto;
      background-color: #fff5f0;
      border-radius: 0.1rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .box-left {
        height: 1.5rem;
        width: 76%;
        display: flex;
        justify-content: space-between;
        .price {
          width: 30%;
          font-size: 0.3rem;
          line-height: 1.5rem;
          text-align: center;
          color: #ff343d;
          span {
            font-size: 0.6rem;
            // font-weight: bold;
          }
        }
        .info {
          width: 70%;
          color: #fe4047;
          margin-top: 0.4rem;
          .max-time {
            font-size: 0.3rem;
          }
          .info-time {
            margin-top: 0.1rem;
            font-size: 0.24rem;
          }
        }
      }
      .box-right {
        width: 24%;
        height: 1.4rem;
        border-left: 1px dotted #ff6a6f;
        color: #ff6a6f;
        text-align: center;
        line-height: 1.4rem;
        font-size: 0.3rem;
      }
    }
  }
  .clear-coupon-btn {
    width: 6.8rem;
    height: 0.8rem;
    margin: 0.2rem auto;
    border-radius: 0.4rem;
    background: #fe4047;
    color: #ffffff;
    text-align: center;
    line-height: 0.8rem;
    font-size: 0.3rem;
  }
  .goods-order {
    display: flex;
    .goods-thumbnail {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 2.52rem;
      height: 1.73rem;
      margin-right: 0.2rem;
      overflow: hidden;
      border-radius: 0.08rem;
      background-color: #e5e5e5;
      > img {
        width: auto;
        height: 100%;
      }
    }
    .gelin {
      width: 1.3007485555555556rem;
    }
    .goods-detail {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      .goods-name {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        max-height: 0.7rem;
        font-size: 0.32rem;
        color: #010101;
        line-height: 0.35rem;
      }
      .goods-info {
        margin-top: 0.15rem;
        color: #969799;
        font-size: 0.24rem;
        .price-market {
          vertical-align: text-bottom;
          font-size: 0.18rem;
          line-height: normal;
          text-decoration: line-through;
        }
        .price-group {
          text-decoration: line-through;
        }
      }
    }
  }
  .goods-coupon {
    margin-top: 0.096rem;
    border-top: 1px solid #dddddd;
    border-bottom: 1px solid #dddddd;
    // padding: .096rem;
    .discount {
      padding: 0.096rem;
      line-height: 1.5;
      font-size: 0.3rem;
      display: flex;
      justify-content: space-between;
      .coupon {
        display: flex;
        align-items: center;
      }
      .price {
        color: #f0423d;
      }
    }
  }
  .member-advert {
    margin: 0.5rem 0;
    .advert-item {
      padding: 0.1rem;
      border: 1px dotted #f0423d;
    }
  }
  .purchase-detail-pay_list {
      // padding: 0 0.192rem;
      background: #ffffff;
      // margin-top: 0.3rem;
      border-radius: 0.1rem;
      .pay_item {
        width: 100%;
        height: 1rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 0.3rem;
        box-sizing: border-box;
        // padding: 0 0.2rem;
        // border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        // &.border-bottom {
        //   border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        // }
        .pay_item_left {
          display: flex;
          align-items: center;
          img {
            width: 0.48rem;
            height: 0.48rem;
            display: block;
            margin-right: 0.14rem;
          }
        }
      }
    }
  .bottom-area {
    height: 1rem;
    .van-submit-bar {
      box-shadow: 0 0 0.1rem 0 rgba(0, 0, 0, 0.1);
    }
  }
}
</style>
